const config_module=require('./config')
const Redis=require('ioredis')

const RedisCli=new Redis({
  host:config_module.redis_host,
  port:config_module.redis_port,
  password:config_module.redis_passwd
})
/**
 * 监听redis错误
 */
RedisCli.on("error",function(err){
  console.log("Redis Error:",err)
  RedisCli.quit()
})
/**
 * 根据key获取value
 * @param{*} key
 * @returns
 */
async function GetRedis(key){
  try{
      const result=await RedisCli.get(key)
      if(result===null){
        console.log('result','<'+key+'>','is null')
        return null
      }
      console.log('result','<'+key+'>','get key success')
      return result
  }catch(error){
      console.log('GetRedis error is: ',error)
      return null
  }
  
}

/**
 * 根据key查询redis是否存在key
 * @param{*} key
 * @returns
 */
 async function QueryRedis(key){
  try{
    const result=await RedisCli.exists(key)
    if(result===0){
      console.log('result','<'+key+'>','is not exist')
      return null
    }
    console.log('result','<'+key+'>','is exist')
    return result
  }catch(error){
    console.log('QueryRedis error is: ',error)
    return null
  }
 }

 /**
  * 添加key和value,并设置过期时间
  * @param{*} key
  * @param{*} value
  * @param{*} expireTime
  * @returns
  */

 async function SetRedisExpire(key,value,expireTime){
  try{
    //设置key和value
    const result=await RedisCli.set(key,value)
    //添加失败
    if(result===null){
      console.log('set key and value error')
      return false
    }
    //设置过期时间
    await RedisCli.expire(key,expireTime)
    return true
  }catch(error){
    console.log('SetRedisExpire error is: ',error)
    return false
  
  }
 }

 /**
  * 退出函数
  */
 function Quit(){
  RedisCli.quit()
 }

 module.exports={GetRedis,QueryRedis,SetRedisExpire,Quit}
